import { getUserLoginInfo } from "@/api/user";
import { getToken, setToken, removeToken, removeMenu } from "@/utils/auth";
import { } from "@/api/user";
import Cookies from "js-cookie";

const getDefaultState = () => {
  return {
    token: getToken()
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  }
};

const actions = {
  setToken({ commit }, token) {
    commit("SET_TOKEN", token);
    setToken(token);
  },

  getUserLoginInfo() {
    return new Promise((resolve, reject) => {
      getUserLoginInfo()
        .then(response => {
          // let menu = {
          //   title: '周日程',
          //   path: 'zrc',
          //   children: [
          //     {
          //       title: '主要领导周日程',
          //       path: '/leader-weekly-schedule',
          //     },
          //     {
          //       title: '科室人员周日程',
          //       path: '/investigator-weekly-schedule',
          //     }
          //   ]
          // }
          // response.data.menus.push(menu)
          Cookies.set("loginInfo", JSON.stringify(response.data.user));
          Cookies.set('userMenu', JSON.stringify(response.data.menus))
          Cookies.set('permissions', JSON.stringify(response.data.permissions))
          // const routersInfo = JSON.parse(Cookies.get('userMenu')) || [];
          // console.log(routersInfo)
          // const dynamicRoutes = loadRoutes(routersInfo);
          // dynamicRoutes.forEach((route) => {
          //   router.addRoute(route);
          // });

          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken(); // must remove  token  first
      removeMenu();
      commit("RESET_STATE");
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
